import axios from 'axios'
import Cookies from 'js-cookie'
import router from '@/router'
import qs from 'qs'
import {
  clearLoginInfo
} from '@/utils'
import isPlainObject from 'lodash/isPlainObject'
import Vue from 'vue'
import VueI18n, {
  messages
} from '@/i18n'
const messagesConst = messages[VueI18n.locale]

const http = axios.create({
  baseURL: window.SITE_CONFIG['apiURL'],
  // baseURL: `/api`,
  timeout: 1000 * 180,
  withCredentials: true
})

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
  config.headers['content-type'] = 'application/json;charset=UTF-8'
  config.headers['Authorization'] = ''
  // config.headers['content-type'] = 'application/x-www-form-urlencoded'
  let urls = ['/auth/login', '/front/consumer/sendVerificationCode', '/front/consumer/checkMessageCode', '/front/consumer/user/register', '/auth/oauth/token']
  if (Cookies.get('access_token') && Cookies.get('access_token') !== 'undefind' && Cookies.get('access_token') !== 'null') {
    if (!urls.includes(config.url)) {
      config.headers['Authorization'] = 'Bearer ' + Cookies.get('access_token') || ''
      config.headers['Token'] = Cookies.get('access_token') || ''
    }
    if (config.url.indexOf('/auth/oauth/token') > -1) {
      config.headers['Authorization'] = 'Bearer ' + Cookies.get('access_token')
      config.headers['Token'] = Cookies.get('access_token') || ''
    }
    if (config.url.indexOf('/front/sso/jwt/username') > -1) {
      config.headers['Authorization'] = ''
      config.headers['Token'] = ''
    }
    // if (!urls.includes(config.url)) {
    //   config.headers['Authorization'] = 'Bearer ' + '34bad7db-c23d-44cd-8893-7dc9920a7384' || ''
    // }
    // if (config.url.indexOf('/auth/oauth/token') > -1) {
    //   config.headers['Authorization'] = 'Bearer ' + '34bad7db-c23d-44cd-8893-7dc9920a7384'
    // }
  }
  // 默认参数
  var defaults = {}
  // 防止缓存，GET请求默认带_t参数
  if (config.method === 'get') {
    config.params = {
      ...config.params,
      ...{
        '_t': new Date().getTime()
      }
    }
  }
  if (isPlainObject(config.params)) {
    config.params = {
      ...defaults,
      ...config.params
    }
  }
  if (isPlainObject(config.data)) {
    config.data = {
      ...defaults,
      ...config.data
    }
    if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
      config.data = qs.stringify(config.data)
    }
  }
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  // login处理
  if (response.data.access_token) {
    response.data['data'] = response.data
    response.data['code'] = 0
  }
  // 返回体Data转成data
  if (response.data.Data) {
    response.data['data'] = response.data.Data
  }
  if (response.data.data) {
    if (response.data.data.count) {
      response.data.data.count = Number(response.data.data.count)
    }
  }
  if (response.data.code === 401 || response.data.code === 10001) {
    // clearLoginInfo()
    // router.replace({
    //   name: 'login'
    // })
    // return Promise.reject(response.data.msg)
  }
  if (response.data.code !== 0 && response.data.code !== 10004 && response.data.code !== 10007) {
    if (response.data.message === '企业ID不能为空') {
      Vue.prototype.$message.warning('该企业未入驻!')
    } else if (response.data.message === 'id_token不能为空') {
      Vue.prototype.$message.warning('身份验证失效,请登录！')
    } else if (response.data.message === '身份验证失效') {
      Vue.prototype.$message.warning('身份验证失效,请重新登录！')
    } else if (response.data.message === '解析用户信息失败') {
      Vue.prototype.$message.warning('身份验证失效,请重新登录！')
    } else {
      Vue.prototype.$message.warning(response.data.message)
    }
    // throw response.data
  }
  return response
}, error => {
  if (error.request.status === 401) {
    clearLoginInfo()
    // router.replace({
    //   name: 'jump'
    // })
  } else {
    Vue.prototype.$message.error(messagesConst.prompt.error || (error.response ? error.response.data.message : ''))
  }
  return Promise.reject(error)
})

export default http
